package com.taotao.service.ipml;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.ExceptionUtil;
import com.taotao.common.utils.HttpClientUtil;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.service.IContentService;

/**
 * 内容管理
 * 
 * @author Administrator
 *
 */
@Service
public class ContentServiceIpml implements IContentService {

	@Autowired
	private TbContentMapper contentMapper;

	@Value(value = "${REST_BASE_URL}")
	private String REST_BASE_URL;

	@Value(value = "${REST_CONTENT_SYNC_URL}")
	private String REST_CONTENT_SYNC_URL;

	/**
	 * 通过内容分类获取全部内容
	 */
	@Override
	public EUDataGridResult getContentList(Long categoryId, Integer page,
			Integer rows) {
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(categoryId);
		// 查找全部内容
		PageHelper.startPage(page, rows);
		List<TbContent> tbContents = this.contentMapper
				.selectByExample(example);
		EUDataGridResult eudr = new EUDataGridResult();
		PageInfo<TbContent> pageInfo = new PageInfo<TbContent>(tbContents);
		long total = pageInfo.getTotal();
		eudr.setTotal(total);
		eudr.setRows(tbContents);
		return eudr;
	}

	/**
	 * 保存内容信息
	 */
	@Override
	public TaotaoResult saveContent(TbContent content) {
		Date date = new Date();
		content.setCreated(date);
		content.setUpdated(date);
		this.contentMapper.insertSelective(content);
		try {
			// http://localhost:8081/rest/redis/sync/content/89
			System.out.println(REST_BASE_URL + REST_CONTENT_SYNC_URL + "/"
					+ content.getCategoryId());
			String result = HttpClientUtil.doGet(REST_BASE_URL
					+ REST_CONTENT_SYNC_URL + "/" + content.getCategoryId());
			TaotaoResult taotaoResult = JsonUtils.jsonToPojo(result,
					TaotaoResult.class);
			if (taotaoResult.getStatus() != 200) {
				throw new Exception();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
		}
		return TaotaoResult.ok();
	}

}
